//
//  RefreshView.m
//  refresh
//
//  Created by 张雪东 on 15/9/24.
//  Copyright (c) 2015年 张雪东. All rights reserved.
//

#import "RefreshView.h"

#define kRefreshViewHeight 64

typedef NS_ENUM(NSInteger, RefreshState) {
    RefreshStateDefault = 0,
    RefreshStateVisible = 1,
    RefreshStateTrigger = 2,
    RefreshStateLoading = 3
};

@interface RefreshView()<UIScrollViewDelegate>{

    CGFloat _currentOffsetY;
}

@property (nonatomic,strong) UIScrollView * scrollView;
@property (nonatomic,strong) UIImageView * imageView;
@property (nonatomic,strong) UIImageView * circleImageView;
@property (nonatomic, assign) RefreshState refreshState;
@property (nonatomic, assign) UIEdgeInsets  originalContentInset;
@end

@implementation RefreshView

- (instancetype)initInScrollView:(UIScrollView *)scrollView{

    self = [super initWithFrame:CGRectMake(0, scrollView.contentInset.top, scrollView.frame.size.width,kRefreshViewHeight)];
    if (self) {
        
        self.scrollView = scrollView;
        self.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        self.backgroundColor = [UIColor clearColor];
        [self.scrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
        [self.scrollView.superview insertSubview:self belowSubview:scrollView];
        NSLog(@"%@",self.scrollView.superview);
        [self loadComponent];
    }
    return self;
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{

    if ([keyPath isEqualToString:@"contentOffset"]) {
        
        _currentOffsetY = [[change valueForKey:NSKeyValueChangeNewKey] CGPointValue].y;
        
        if (_currentOffsetY < 0 && self.refreshState == RefreshStateDefault) {
            
            self.imageView.center = CGPointMake(self.frame.size.width / 2, - self.frame.size.height / 2 - _currentOffsetY);
        }
        if(_currentOffsetY <= - kRefreshViewHeight && self.refreshState == RefreshStateDefault){
            self.refreshState = RefreshStateTrigger;
            self.imageView.center = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2);
        }
        if (!self.scrollView.isDragging && self.refreshState == RefreshStateTrigger) {
            [UIView animateWithDuration:0.35 animations:^{
                self.scrollView.contentInset = UIEdgeInsetsMake(kRefreshViewHeight, 0, 0, 0);
            }];
            _circleImageView.hidden = NO;
            [self ballAnimation];
            self.refreshState = RefreshStateLoading;
            NSNotificationCenter * notificationCenter = [NSNotificationCenter defaultCenter];
            [notificationCenter postNotificationName:@"loading" object:nil];
        }
    }
}

-(void)setRefreshState:(RefreshState)refreshState{

    _refreshState = refreshState;
    
    switch (refreshState) {
        case RefreshStateDefault:
            
            break;
        case RefreshStateTrigger:{
            
            
        }
            break;
        default:
            break;
    }
}

- (void)ballAnimation {
    CABasicAnimation *enlarge = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    enlarge.duration = .5;
    enlarge.repeatCount = 1;
    enlarge.removedOnCompletion = NO;
    enlarge.fromValue = [NSNumber numberWithFloat:.5];
    enlarge.toValue = [NSNumber numberWithFloat:1];
    CABasicAnimation *decrease = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    decrease.duration = .5;
    decrease.repeatCount = 1;
    decrease.removedOnCompletion = NO;
    decrease.beginTime = .5;
    decrease.fromValue = [NSNumber numberWithFloat:1];
    decrease.toValue = [NSNumber numberWithFloat:.5];
    CABasicAnimation *position = [CABasicAnimation animationWithKeyPath:@"position"];
    position.duration = 1;
    position.repeatCount = MAXFLOAT;
    position.fromValue = [NSValue valueWithCGPoint:self.circleImageView.center];
    position.toValue = [NSValue valueWithCGPoint:CGPointMake(self.circleImageView.center.x, self.circleImageView.center.y + 15)];
    CAAnimationGroup *group = [CAAnimationGroup animation];
    group.duration = 1;
    group.repeatCount = MAXFLOAT;
    group.removedOnCompletion = NO;
    group.autoreverses = YES;
    group.animations = [NSArray arrayWithObjects:enlarge, decrease, position, nil];
    [self.circleImageView.layer addAnimation:group forKey:@"CCEaseRefresh"];
}

-(void)loadComponent{

    UIImage * image = [UIImage imageNamed:@"refresh_sphere-1"];
    UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
    imageView.center = CGPointMake(self.frame.size.width / 2, - self.frame.size.height / 2);
    self.imageView = imageView;
    imageView.image = image;
    [self addSubview:imageView];
    
    UIImage * circleImage = [UIImage imageNamed:@"refresh_circle-1"];
    UIImageView * circleImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, circleImage.size.width, circleImage.size.height)];
    circleImageView.image = circleImage;
    circleImageView.hidden = YES;
    self.circleImageView = circleImageView;
    circleImageView.center = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2 - 7.5);
    [self addSubview:circleImageView];
}

-(void)endRefreshing{

    [UIView animateWithDuration:0.35 animations:^{
        self.scrollView.contentInset = UIEdgeInsetsZero;
    }];
    _circleImageView.hidden = YES;
    self.refreshState = RefreshStateDefault;
    _imageView.center = CGPointMake(self.frame.size.width / 2, - self.frame.size.height / 2);
}


-(void)setScrollView:(UIScrollView *)scrollView{

    _scrollView = scrollView;
    _originalContentInset = scrollView.contentInset;
    _scrollView.backgroundColor = [UIColor clearColor];
}

@end
